﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Main_Ledger_Ledger : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    string strsql = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!IsPostBack)
        {
            //************Table for Delivery Address*//
            DataTable DTDeliveryAddress = new DataTable();
            DTDeliveryAddress.Columns.Add("TITLE", typeof(string));
            DTDeliveryAddress.Columns.Add("CONTACTNAME", typeof(string));
            DTDeliveryAddress.Columns.Add("ADD1", typeof(string));
            DTDeliveryAddress.Columns.Add("ADD2", typeof(string));
            DTDeliveryAddress.Columns.Add("ADD3", typeof(string));
            DTDeliveryAddress.Columns.Add("ADD4", typeof(string));
            DTDeliveryAddress.Columns.Add("PINCODE", typeof(string));
            DTDeliveryAddress.Columns.Add("STATEID", typeof(string));
            DTDeliveryAddress.Columns.Add("STATE", typeof(string));
            DTDeliveryAddress.Columns.Add("COUNTRY", typeof(string));
            DTDeliveryAddress.Columns.Add("place", typeof(string));
            DTDeliveryAddress.Columns.Add("fax", typeof(string));
            DTDeliveryAddress.Columns.Add("phone", typeof(string));
            DTDeliveryAddress.Columns.Add("LSTNUM", typeof(string));
            DTDeliveryAddress.Columns.Add("LSTDATE", typeof(string));
            DTDeliveryAddress.Columns.Add("CSTNUM", typeof(string));
            DTDeliveryAddress.Columns.Add("CSTDATE", typeof(string));
            DTDeliveryAddress.Columns.Add("CEPANUM", typeof(string));
            DTDeliveryAddress.Columns.Add("CEPADATE", typeof(string));
            ViewState["DTDeliveryAddress"] = DTDeliveryAddress;
            //*************

            _BindItemGroup();
            _BindDDLServices();
            _BindNameTitle(ddlName);
            _BindNameTitle(DDLDileveryName);
            _BindState();
            _BindCountry();
            _BindTaxType();
            _BindTermAndCondition();
            _EnableControl();
            _BindTaxGroupSales();
            _BindTaxGroupPurchase();
            _DisableAllTab();
            _BindTDSStatusAndNature();
        }

    }
    #region data binding functions
    private void _BindItemGroup()
    {
        strsql = "select GID,PID,GROUPTREEID,GNAME from ACC_GRPMAST where gid<>pid Order By GNAME";
        DataTable DTGroup = DU.getdata(strsql);
        DDLGroupName.Items.Clear();
        DDLGroupName.DataSource = DTGroup;
        DDLGroupName.DataTextField = "GNAME";
        DDLGroupName.DataValueField = "GID";
        DDLGroupName.DataBind();
        DDLGroupName.Items.Insert(0, new ListItem("", "0"));


    }
    private void _BindTermAndCondition()
    {
        strsql = "select TRMID,TRMDESC from ACC_TERMSCONDITIONS Order By TRMDESC ASC";
        DataTable dt = DU.getdata(strsql);
        lstTermCondition.DataSource = dt;
        lstTermCondition.DataTextField = "TRMDESC";
        lstTermCondition.DataValueField = "TRMID";
        lstTermCondition.DataBind();
        lstTermCondition.Items.Insert(0, new ListItem("", "0"));
        lstTermCondition.SelectedValue = "0";
    }
    private void _BindDDLServices()
    {
        DDLServices.Items.Add(new ListItem("Debit", "0"));
        DDLServices.Items.Add(new ListItem("Credit", "1"));
        DDLServices.SelectedValue = "0";
    }
    private void _BindNameTitle(DropDownList ddl)
    {
        ddl.Items.Add(new ListItem(" ", "0"));
        ddl.Items.Add(new ListItem("M/s", "1"));
        ddl.Items.Add(new ListItem("Mr.", "2"));
        ddl.Items.Add(new ListItem("Mrs.", "3"));
        ddl.Items.Add(new ListItem("Ms.", "4"));

    }
    private void _BindCountry()
    {
        strsql = "select CountryId,CountryName from MAS_Country";
        DataTable dt = DU.getdata(strsql);
        ddlCountry.DataSource = dt;
        ddlCountry.DataTextField = "CountryName";
        ddlCountry.DataValueField = "CountryId";
        ddlCountry.DataBind();
        DDLDileveryCountry.DataSource = dt;
        DDLDileveryCountry.DataTextField = "CountryName";
        DDLDileveryCountry.DataValueField = "CountryId";
        DDLDileveryCountry.DataBind();

    }
    private void _BindState()
    {
        strsql = "select StateId,StateName from MAS_State";
        DataTable DT = DU.getdata(strsql);
        ddlState.DataSource = DT;
        ddlState.DataTextField = "StateName";
        ddlState.DataValueField = "StateId";
        ddlState.DataBind();
        ddlState.Items.Insert(0, new ListItem("---Select State---", "0"));
        ddlState.SelectedValue = "0";
        DDLDileveryState.DataSource = DT;
        DDLDileveryState.DataTextField = "StateName";
        DDLDileveryState.DataValueField = "StateId";
        DDLDileveryState.DataBind();
        DDLDileveryState.Items.Insert(0, new ListItem("---Select State---", "0"));
        DDLDileveryState.SelectedValue = "0";
    }
    private void _BindTaxType()
    {
        
        DataTable DT = DU.getdatausingprocedure("USP_ACC_GetTaxTypeDetails");
        DDLTaxType.DataSource = DT;
        DDLTaxType.DataTextField = "TAXTYPE";
        DDLTaxType.DataValueField = "TAXTYPEID";
        DDLTaxType.DataBind();
        DDLTaxType.Items.Insert(0, new ListItem("", "0"));
    }
    private void _BindTDSStatusAndNature()
    {
        strsql = "SELECT MAINCLASSID, MAINCLASSNAME FROM ACC_TAXMAINCLASS WHERE TAXTYPEID='13'";
        DataTable DTNature = DU.getdata(strsql);
        ddlTDSNature.DataSource = DTNature;
        ddlTDSNature.DataTextField = "MAINCLASSNAME";
        ddlTDSNature.DataValueField = "MAINCLASSID";
        ddlTDSNature.DataBind();
        ddlTDSNature.Items.Insert(0, new ListItem("", "0"));

        strsql = "SELECT SUBCLASSID, SUBCLASSNAME FROM ACC_TAXSUBCLASS WHERE SUBCLASSID IN(44,61,62,63,64,65,66,67,68,69)";
        DataTable DTStatus = DU.getdata(strsql);
        DDLStatus.DataSource = DTStatus;
        DDLStatus.DataTextField = "SUBCLASSNAME";
        DDLStatus.DataValueField = "SUBCLASSID";
        DDLStatus.DataBind();
        DDLStatus.Items.Insert(0, new ListItem("", "0"));
    }
    private void _BindTaxMainClass()
    {
        SqlParameter[] sparam =
                                {
                                    new SqlParameter("@TAXTYPEID",DDLTaxType.SelectedValue)
                                };

        DataTable DT = DU.getdatausingprocedure("USP_ACC_GetTaxMainClassNames", sparam);
        if (DT.Rows.Count > 0)
        {
            DDLMainClass.DataSource = DT;
            DDLMainClass.DataTextField = "MAINCLASSNAME";
            DDLMainClass.DataValueField = "MAINCLASSID";
            DDLMainClass.DataBind();
        }
        else
        {
            DDLMainClass.Enabled = false;

        }

    }
    private void _BindTaxSubClass()
    {
        SqlParameter[] sparam =
                                {
                                    new SqlParameter("@TAXTYPEID",DDLTaxType.SelectedValue),
                                    new SqlParameter("@MAINCLASSID",DDLMainClass.SelectedValue)
                                };

        DataTable DT = DU.getdatausingprocedure("USP_ACC_GetLedTaxSubClass", sparam);
        if (DT.Rows.Count > 0)
        {
            DDLSubClass.Enabled = true;
            DDLSubClass.DataSource = DT;
            DDLSubClass.DataTextField = "SUBCLASSNAME";
            DDLSubClass.DataValueField = "SUBCLASSID";
            DDLSubClass.DataBind();
        }
        else
        {
            DDLSubClass.Enabled = false;
        }
    }
    private void _BindTaxGroupPurchase()
    {
        DataTable DTPurchase = DU.getdatausingprocedure("USP_ACC_GetPurchaseMainClass");
        ddlPurchase.DataSource = DTPurchase;
        ddlPurchase.DataTextField = "MAINCLASSNAME";
        ddlPurchase.DataValueField = "MAINCLASSID";
        ddlPurchase.DataBind();
        ddlPurchase.Items.Insert(0, new ListItem("", "0"));
    }
    private void _BindTaxGroupSales()
    {
        DataTable DTSales = DU.getdatausingprocedure("USP_ACC_GetSalesMainClass");
        ddlSales.DataSource = DTSales;
        ddlSales.DataTextField = "MAINCLASSNAME";
        ddlSales.DataValueField = "MAINCLASSID";
        ddlSales.DataBind();
        ddlSales.Items.Insert(0, new ListItem("", "0"));

    }
    private void _BindLedger()
    {
        strsql = "select LID,LNAME from ACC_LEDMAST where ALWSUB='True' Order by Lname";
        DataTable DT = DU.getdata(strsql);
        DDLGroupName.Items.Clear();
        DDLGroupName.DataSource = DT;
        DDLGroupName.DataTextField = "LNAME";
        DDLGroupName.DataValueField = "LID";
        DDLGroupName.DataBind();
        DDLGroupName.Items.Insert(0, new ListItem("", "0"));
    }
    #endregion
    #region Event Related Functions
    protected void ddlPurchase_SelectedIndexChanged(object sender, EventArgs e)
    {
        if ((Convert.ToInt32(ddlPurchase.SelectedValue) == 1) || (Convert.ToInt32(ddlPurchase.SelectedValue) == 2))
        {
            ddlSales.SelectedValue = "3";
        }
        else if (Convert.ToInt32(ddlPurchase.SelectedValue) == 5)
        {
            ddlSales.SelectedValue = "6";
        }
        else
        {
            ddlSales.SelectedValue = "0";
        }
    }
    protected void ddlSales_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (Convert.ToInt32(ddlSales.SelectedValue) == 3)
        {
            ddlPurchase.SelectedValue = "1";
        }
        else if (Convert.ToInt32(ddlSales.SelectedValue) == 6)
        {
            ddlPurchase.SelectedValue = "5";
        }
        else
        {
            ddlPurchase.SelectedValue = "0";
        }
    }
    protected void DDLTaxType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (Convert.ToInt32(DDLTaxType.SelectedValue) > 0)
        {
            DDLMainClass.Enabled = true;
            _BindTaxMainClass();

            DDLSubClass.Items.Clear();
            DDLSubClass.Items.Insert(0, new ListItem("", "0"));
            DDLSubClass.Enabled = false;

        }
        else
        {
            DDLMainClass.Items.Clear();
            DDLMainClass.Items.Insert(0, new ListItem("", "0"));
            DDLMainClass.Enabled = false;

        }
    }
    protected void DDLMainClass_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (Convert.ToInt32(DDLMainClass.SelectedValue) > 0)
        {
            DDLSubClass.Enabled = true;
            _BindTaxSubClass();

        }
        else
        {
            DDLSubClass.Items.Clear();
            DDLSubClass.Items.Insert(0, new ListItem("", "0"));
            DDLSubClass.Enabled = false;
        }
    }
    protected void DDLGroupName_SelectedIndexChanged(object sender, EventArgs e)
    {
        _DeleteZeroValueItemInDropdownlist(DDLGroupName);
        _EnableBillWise();
        string strGID = string.Empty;
        if (ChkSubLedger.Checked == true)
        {
            strsql = "SELECT PGID FROM ACC_LEDMAST WHERE LID='" + DDLGroupName.SelectedValue + "'";
            DataTable DTGid = DU.getdata(strsql);
            if (DTGid.Rows.Count > 0)
            {
                strGID = DTGid.Rows[0]["PGID"].ToString();
            }
        }
        else
        {
            strGID = DDLGroupName.SelectedValue;
        }
        _ApplySettings(strGID);
    }
    protected void ChkSubLedger_CheckedChanged(object sender, EventArgs e)
    {
        if (ChkSubLedger.Checked == true)
        {
            _BindLedger();
            CHKAllow.Checked = false;
            TxtOpeningBal.Enabled = true;
            DDLServices.Enabled = true;
        }
        else if (ChkSubLedger.Checked == false)
        {
            _BindItemGroup();

        }
    }
    protected void CHKAllow_CheckedChanged(object sender, EventArgs e)
    {
        if (CHKAllow.Checked == true)
        {
            _BindItemGroup();
            ChkSubLedger.Checked = false;
            TxtOpeningBal.Text = "0.00";
            TxtClosing.Text = "";
            TxtOpeningBal.Enabled = false;
            DDLServices.Enabled = false;
        }
        else if (CHKAllow.Checked == false)
        {
            TxtOpeningBal.Enabled = true;
            DDLServices.Enabled = true;
        }
    }
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        //try
        //{
            if (_ValidateLedger1() && _ValidateLedger() && _ValidateGroup() && _ValidateGroup1())
            {
                _SaveLedger("-1");
            }
        //}
        //catch (Exception ex)
        //{
        //    lblMsg.Attributes.Remove("class");
        //    lblMsg.Attributes.Add("class", "false");
        //    lblMsg.Text = ex.Message;
        //}
    }
    protected void BtnClose_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Welcome.aspx");
    }
    protected void btnSaveDelivery_Click(object sender, EventArgs e)
    {
        _GetDeliveryAddressDetails();
        modalDelivery.Show();
    }
    protected void btnCancelDelivery_Click(object sender, EventArgs e)
    {
        modalDelivery.Hide();
    }
    #endregion
    #region Validations Functions
    private void _EnableBillWise()
    {
        SqlParameter[] sparam =
                                {
                                    new SqlParameter("@IsSubLed",ChkSubLedger.Checked),
                                    new SqlParameter ("@Id",DDLGroupName.SelectedValue)
                                };
        DataTable DT = DU.getdatausingprocedure("USP_GetBillWiseLedger", sparam);
        if (DT.Rows.Count > 0)
        {
            if (Convert.ToInt32(DT.Rows[0]["GID"].ToString()) > 0)
            {
                CHKBillWise.Checked = true;
                CHKBillWise.Enabled = true;
            }
            else
            {

                CHKBillWise.Checked = false;
                CHKBillWise.Enabled = false;
            }
        }
    }
    private void _EnableControl()
    {
        strsql = "Select * from IVR_SETTINGS";
        DataTable DTEnable = DU.getdata(strsql);
        if (DTEnable.Rows.Count > 0)
        {
            if (DTEnable.Rows[0]["TCS"].ToString() == "True")
            {
                chkApplyTCS.Enabled = true;
            }
            else
            {
                chkApplyTCS.Checked = false;
                chkApplyTCS.Enabled = false;
            }
            lblSalesPersonMain.Text = DTEnable.Rows[0]["OTHSALEPERSONCAP"].ToString();
        }
    }
    private bool _ValidateLedger1()
    {
        strsql = "Select LID from ACC_LEDMAST Where (LANAME='" + TxtAlterName.Text + "' OR LNAME='" + TxtAlterName.Text + "')AND LANAME<>''";
        DataTable DTAName = DU.getdata(strsql);
        if (DTAName.Rows.Count > 0)
        {
            lblMsg.Attributes.Remove("class");
            lblMsg.Attributes.Add("class", "false");
            lblMsg.Text = "Duplicate Alternate Ledger Name";
            TxtAlterName.Focus();
            return false;
        }
        else
        {
            return true;
        }
    }
    private bool _ValidateGroup1()
    {
        strsql = "Select GID from ACC_GRPMAST Where (GANAME='" + TxtAlterName.Text + "' OR GNAME='" + TxtAlterName.Text + "')AND GANAME<>''";
        DataTable DTGName = DU.getdata(strsql);
        if (DTGName.Rows.Count > 0)
        {
            lblMsg.Attributes.Remove("class");
            lblMsg.Attributes.Add("class", "false");
            lblMsg.Text = "Group Name Have Already This Alternate Name";
            TxtAlterName.Focus();
            return false;
        }
        else
        {
            return true;
        }

    }
    private bool _ValidateLedger()
    {
        strsql = "Select LID from ACC_LEDMAST Where LNAME='" + TxtName.Text + "'OR LANAME='" + TxtName.Text + "'";
        DataTable DTName = DU.getdata(strsql);
        if (DTName.Rows.Count > 0)
        {
            lblMsg.Text = "Duplicate Ledger Name";
            TxtName.Focus();
            return false;
        }
        else
        {
            return true;
        }
    }
    private bool _ValidateGroup()
    {
        strsql = "Select GID from ACC_GRPMAST Where GANAME='" + TxtName.Text + "' OR GNAME='" + TxtName.Text + "'";
        DataTable DTGName = DU.getdata(strsql);
        if (DTGName.Rows.Count > 0)
        {
            lblMsg.Attributes.Remove("class");
            lblMsg.Attributes.Add("class", "false");
            lblMsg.Text = "Group Name Have Already This Name";
            TxtName.Focus();
            return false;
        }
        else
        {
            return true;
        }

    }
    #endregion
    #region Database Related Function for Insert Data Into Database
    private void _SaveLedger(string strLid)
    {
        try
        {
            double openingBal = 0;
            if (TxtOpeningBal.Text == string.Empty)
            {
                TxtOpeningBal.Text = "0";
            }
            openingBal = Convert.ToDouble(TxtOpeningBal.Text.Trim());
            if (openingBal > 0)
            {
                if (DDLServices.SelectedItem.Text == "Debit")
                {
                    openingBal = 0 - openingBal;
                }
            }
            SqlParameter[] sparam ={
                                     new SqlParameter("@LID",strLid),
                                     new SqlParameter("@PGID",DDLGroupName.SelectedValue),
                                     new SqlParameter("@PLID","0"),
                                     new SqlParameter("@LNAME",TxtName.Text.Trim()),
                                     new SqlParameter("@LANAME",TxtAlterName.Text.Trim()),
                                     new SqlParameter("@ACTOPENING",openingBal.ToString()),
                                     new SqlParameter("@BILLWISE",CHKBillWise.Checked),
                                     new SqlParameter("@ALWSUB",CHKAllow.Checked),
                                     new SqlParameter("@TAXAPPLY",ChkTaxType.Checked ),
                                     new SqlParameter("@COSTCENTREAPPLY",ChkCost.Checked),
                                     new SqlParameter("@TDSAPPLY",ChkTDS.Checked),
                                     new SqlParameter("@STAPPLY",ChkService.Checked),
                                     new SqlParameter("@SUBLEDGERACC",ChkSubLedger.Checked),
                                     new SqlParameter("@TRANSPORTER","0"),
                                     new SqlParameter("@CName",Session["username"].ToString())
                                };
            strLid = DU.ExecuteProcedure_Scope_Identity("USP_ACC_SaveLedger", sparam);
            if (strLid != string.Empty && strLid != "-1")
            {
                _SaveContactDetails(strLid);
                _SaveDeliveryDetails(strLid);
                _SaveAddressDetails(strLid);
                _SaveTermAndConditions(strLid);
                _SaveRegistrationDetails(strLid);
                _SaveOthersDetails(strLid);
                _SaveTaxDetails(strLid);
                lblMsg.Text = "Ledger Created successfuly...";
            }
        }
        catch (Exception ex)
        {
        //    lblMsg.Attributes.Remove("class");
        //    lblMsg.Attributes.Add("class", "false");
        //    lblMsg.Text = ex.Message;
        }
    }
    private void _SaveContactDetails(string strLid)
    {
        if (strLid != string.Empty)
        {
            SqlParameter[] sparam = 
                                    { 
                                        new SqlParameter("@LID",strLid),
                                        new SqlParameter("@CONTACTID ","0"),
                                        new SqlParameter("@PERSON",txtContactPerson.Text.Trim()),
                                        new SqlParameter("@POSITION",txtContactPosition.Text.Trim()),
                                        new SqlParameter("@PHONENUM",txtContactPhone.Text.Trim()),
                                        new SqlParameter("@MOBILENUM",txtContactMobile.Text.Trim()),
                                        new SqlParameter("@EMAIL",txtContactEmail.Text.Trim()),
                                        new SqlParameter("@FAXNUM",txtContactFax.Text.Trim()),
                                        new SqlParameter("@REMARKS",txtContactRemarks.Text.Trim()),
                                        new SqlParameter("@CNAME",Session["username"].ToString()),     
                                    };
            DU.executeprocedure("USP_ACC_SaveLedgerContactDetails", sparam);

        }
    }
    private void _SaveDeliveryDetails(string strLid)
    {

        string LstDate = string.Empty;
        string CstDate = string.Empty;
        string CepDate = string.Empty;
        if (txtDeliveryVatDate.Text.Trim() != string.Empty)
        {
            string[] lst = txtDeliveryVatDate.Text.ToString().Split('/');
            LstDate = lst[1].ToString() + "/" + lst[0].ToString() + "/" + lst[2].ToString();
        }
        if (txtDeliveryInterStateDate.Text.Trim() != string.Empty)
        {
            string[] cst = txtDeliveryInterStateDate.Text.ToString().Split('/');
            CstDate = cst[1].ToString() + "/" + cst[0].ToString() + "/" + cst[2].ToString();
        }

        if (txtDeliveryCENVATDate.Text.Trim() != string.Empty)
        {
            string[] cep = txtDeliveryCENVATDate.Text.ToString().Split('/');
            CepDate = cep[1].ToString() + "/" + cep[0].ToString() + "/" + cep[2].ToString();
        }
        if (txtDileveryName.Text != string.Empty && strLid != string.Empty)
        {

            SqlParameter[] sparam = 
                                        {
                                            new SqlParameter("@LID", strLid),
                                            new SqlParameter("@TITLE",DDLDileveryName.SelectedItem.Text.Trim()),
                                            new SqlParameter("@CONTACTNAME",txtDileveryName.Text.Trim()),
                                            new SqlParameter("@ADD1",txtDileveryAddress1.Text.Trim()),
                                            new SqlParameter("@ADD2",txtDileveryAddress2.Text.Trim()),
                                            new SqlParameter("@ADD3",txtDileveryAddress3.Text.Trim()),
                                            new SqlParameter("@ADD4",txtDileveryAddress4.Text.Trim()),
                                            new SqlParameter("@PINCODE",txtDileveryPincode.Text.Trim()),
                                            new SqlParameter("@STATEID",DDLDileveryState.SelectedValue),
                                            new SqlParameter("@COUNTRY",DDLDileveryCountry.SelectedItem.Text.Trim()),
                                            new SqlParameter("@place", TxtDileveryPlace.Text.Trim()),
                                            new SqlParameter("@fax", TxtDileveryFax.Text.Trim()),
                                            new SqlParameter("@phone", TxtDileveryPhone.Text.Trim()),
                                            new SqlParameter("@LSTNUM",txtVat.Text.Trim()),
                                            new SqlParameter("@LSTDATE",LstDate),
                                            new SqlParameter("@CSTNUM",txtDeliveryInterState.Text.Trim()),
                                            new SqlParameter("@CSTDATE",CstDate.ToString()),
                                            new SqlParameter("@CEPANUM",txtDeliveryCENVAT.Text.Trim()),
                                            new SqlParameter("@CEPADATE",CepDate.ToString()),
                                            new SqlParameter("@CName",Session["username"].ToString())
                                        };
            int result = DU.executeprocedure("USP_ACC_SaveLedgerDeliveryAddressDetails", sparam);
        }
    }
    private void _SaveAddressDetails(string strLid)
    {
        if (strLid != string.Empty)
        {
            SqlParameter[] sparam = 
                                        {                                           
                                            new SqlParameter("@LID",strLid),
                                            new SqlParameter("@ADDRESSID","0"),
                                            new SqlParameter("@TITLE",ddlName.SelectedItem.Text.Trim()),
                                            new SqlParameter("@LNAME",txtAddName.Text.Trim()),
                                            new SqlParameter("@ADDRESS1",txtAddress1.Text.Trim()),
                                            new SqlParameter("@ADDRESS2",txtAddress2.Text.Trim()),
                                            new SqlParameter("@ADDRESS3",txtAddress3.Text.Trim()),
                                            new SqlParameter("@PLACE",txtAddPlace.Text.Trim()),
                                            new SqlParameter("@PINCODE",txtPin.Text.Trim()),
                                            new SqlParameter("@STATEID",ddlState.SelectedValue),
                                            new SqlParameter("@COUNTRY",ddlCountry.SelectedItem.Text),
                                            new SqlParameter("@WEBSITE",txtWebsite.Text.Trim()),
                                            new SqlParameter("@EMAIL",txtEmail.Text.Trim()),
                                            new SqlParameter("@PHONE",txtPhone.Text.Trim()),
                                            new SqlParameter("@FAX",txtFax.Text.Trim()),
                                            new SqlParameter("@CNAME",Session["username"].ToString()),
                                        };
            DU.executeprocedure("USP_ACC_SaveLedgerAddressDetails", sparam);
        }
    }
    private void _SaveTermAndConditions(string strLid)
    {
        if (Convert.ToInt32(lstTermCondition.SelectedValue) > 0 && strLid != string.Empty)
        {
            SqlParameter[] sparam =
                                        {
                                            new SqlParameter("@LEDTRMID","0"),
                                            new SqlParameter("@LID",strLid),
                                            new SqlParameter("@TRMID",lstTermCondition.SelectedValue)
                                        };
            DU.executeprocedure("USP_ACC_SaveLedgerTermsCondition", sparam);
        }
    }
    private void _SaveRegistrationDetails(string strLid)
    {
        string PANDate = string.Empty;
        string VatDate = string.Empty;
        string CSTDate = string.Empty;
        string TDSDate = string.Empty;
        string STDate = string.Empty;
        string LTDate = string.Empty;
        string CENVATDate = string.Empty;
        if (txtRegPANDate.Text != string.Empty)
        {
            string[] pan = txtRegPANDate.Text.ToString().Split('/');
            PANDate = pan[1].ToString() + "/" + pan[0].ToString() + "/" + pan[2].ToString();
        }
        if (txtRegVATDate.Text != string.Empty)
        {
            string[] vat = txtRegVATDate.Text.ToString().Split('/');
            VatDate = vat[1].ToString() + "/" + vat[0].ToString() + "/" + vat[2].ToString();
        }
        if (txtRegInterStateDate.Text != string.Empty)
        {
            string[] cst = txtRegInterStateDate.Text.ToString().Split('/');
            CSTDate = cst[1].ToString() + "/" + cst[0].ToString() + "/" + cst[2].ToString();
        }
        if (txtRegTaxDeductionDate.Text != string.Empty)
        {
            string[] tds = txtRegTaxDeductionDate.Text.ToString().Split('/');
            TDSDate = tds[1].ToString() + "/" + tds[0].ToString() + "/" + tds[2].ToString();
        }
        if (txtRegServiceTaxDate.Text != string.Empty)
        {
            string[] st = txtRegServiceTaxDate.Text.ToString().Split('/');
            STDate = st[1].ToString() + "/" + st[0].ToString() + "/" + st[2].ToString();
        }
        if (txtRegLuxuryDate.Text != string.Empty)
        {
            string[] lt = txtRegLuxuryDate.Text.ToString().Split('/');
            LTDate = lt[1].ToString() + "/" + lt[0].ToString() + "/" + lt[2].ToString();
        }
        if (txtRegCVNNETDate.Text != string.Empty)
        {
            string[] cenvat = txtRegCVNNETDate.Text.ToString().Split('/');
            CENVATDate = cenvat[1].ToString() + "/" + cenvat[0].ToString() + "/" + cenvat[2].ToString();
        }
        if (strLid != string.Empty)
        {
            SqlParameter[] sparam =  {
                                            new SqlParameter("@LID",strLid),
                                            new SqlParameter("@REGID","0"),
                                            new SqlParameter("@PAN",txtRegPAN.Text.Trim()),
                                            new SqlParameter("@PANDATE",PANDate.ToString()),
                                            new SqlParameter("@VATTIN",txtRegVAT.Text.Trim()),
                                            new SqlParameter("@VATTINDATE",VatDate.ToString()),
                                            new SqlParameter("@CSTNO",txtRegInterState.Text.Trim()),
                                            new SqlParameter("@CSTDATE",CSTDate.ToString()),
                                            new SqlParameter("@TDSNO",txtRegTaxDeduction.Text.Trim()),
                                            new SqlParameter("@TDSDATE",TDSDate.ToString()),
                                            new SqlParameter("@SERTNO",txtRegServicetax.Text.Trim()),
                                            new SqlParameter("@SERTNDATE",STDate.ToString()),
                                            new SqlParameter("@LTNO",txtRegLuxury.Text.Trim()),
                                            new SqlParameter("@LTNDATE",LTDate.ToString()),
                                            new SqlParameter("@CEPAN",txtRegCVNNET.Text.Trim()),
                                            new SqlParameter("@CEPANDATE",CENVATDate.ToString()),
                                            new SqlParameter("@PANREF",txtRegPanRef.Text.Trim()),
                                            new SqlParameter("@CName",Session["username"].ToString())
                                     };
            DU.executeprocedure("USP_ACC_SaveRegistrationDetails", sparam);
        }
    }
    private void _SaveOthersDetails(string strLid)
    {
        if (strLid != string.Empty)
        {
            if (txtCreditPeriod.Text == string.Empty)
            {
                txtCreditPeriod.Text = "0";
            }
            if (txtCreditLimit.Text == string.Empty)
            {
                txtCreditLimit.Text = "0";
            }            
            SqlParameter[] sparam = 
                                        { 
                                            new SqlParameter("@LID",strLid),
                                            new SqlParameter("@ACTIVE",CHKAvtive.Checked),
                                            new SqlParameter("@TCS",chkApplyTCS.Checked),
                                            new SqlParameter("@CREDITPERIOD",txtCreditPeriod.Text.Trim()),
                                            new SqlParameter("@CREDITLIMIT",txtCreditLimit.Text.Trim()),
                                            new SqlParameter("@PURTAXMAINCLASSID",ddlPurchase.SelectedValue),
                                            new SqlParameter("@SALETAXMAINCLASSID",ddlSales.SelectedValue),
                                            new SqlParameter("@SPRID",ddlSalePerson.SelectedValue),
                                            new SqlParameter("@SPGID",ddlPriceGroup.SelectedValue),
                                            new SqlParameter("@SUBTAXID","0"),
                                            new SqlParameter("@CName",Session["username"].ToString())
                                        };
            DU.executeprocedure("USP_ACC_SaveLedgerOtherDetails", sparam);
        }
    }
    private void _SaveTaxDetails(string strLid)
    {
        if (Convert.ToInt32(DDLTaxType.SelectedValue) > 0 && strLid != string.Empty)
        {


            SqlParameter[] sparam = { 
                                            new SqlParameter("@LID",strLid),
                                            new SqlParameter("@TAXTYPEID","-1"),
                                            new SqlParameter("@TAXTYPEID",DDLTaxType.SelectedValue),
                                            new SqlParameter("@MAINCLASSID",DDLMainClass.SelectedValue),
                                            new SqlParameter("@SUBCLASSID",DDLSubClass.SelectedValue),
                                            new SqlParameter("@CName",Session["username"].ToString())
                                        };
            DU.executeprocedure("USP_ACC_SaveLedgerTaxDetails", sparam);

        }
    }
    #endregion
    private void _GetDeliveryAddressDetails()
    {
        string LstDate = string.Empty;
        string CstDate = string.Empty;
        string CepDate = string.Empty;
        if (txtDeliveryVatDate.Text.Trim() != string.Empty)
        {
            string[] lst = txtDeliveryVatDate.Text.ToString().Split('/');
            LstDate = lst[1].ToString() + "/" + lst[0].ToString() + "/" + lst[2].ToString();
        }
        if (txtDeliveryInterStateDate.Text.Trim() != string.Empty)
        {
            string[] cst = txtDeliveryInterStateDate.Text.ToString().Split('/');
            CstDate = cst[1].ToString() + "/" + cst[0].ToString() + "/" + cst[2].ToString();
        }

        if (txtDeliveryCENVATDate.Text.Trim() != string.Empty)
        {
            string[] cep = txtDeliveryCENVATDate.Text.ToString().Split('/');
            CepDate = cep[1].ToString() + "/" + cep[0].ToString() + "/" + cep[2].ToString();
        }
        DataTable DTTemp = new DataTable();
        DTTemp = (DataTable)ViewState["DTDeliveryAddress"];
        DataRow DRDeliveryAdd = DTTemp.NewRow();
        DRDeliveryAdd["TITLE"] = DDLDileveryName.SelectedItem.Text.Trim();
        DRDeliveryAdd["CONTACTNAME"] = txtDileveryName.Text.Trim();
        DRDeliveryAdd["ADD1"] = txtDileveryAddress1.Text.Trim();
        DRDeliveryAdd["ADD2"] = txtDileveryAddress2.Text.Trim();
        DRDeliveryAdd["ADD3"] = txtDileveryAddress3.Text.Trim();
        DRDeliveryAdd["ADD4"] = txtDileveryAddress4.Text.Trim();
        DRDeliveryAdd["PINCODE"] = txtDileveryPincode.Text.Trim();
        DRDeliveryAdd["STATEID"] = DDLDileveryState.SelectedValue;
        if (DDLDileveryState.SelectedValue != "0")
        {
            DRDeliveryAdd["STATE"] = DDLDileveryState.SelectedValue;
        }
        else
        {
            DRDeliveryAdd["STATE"] = "";
        }
        DRDeliveryAdd["COUNTRY"] = DDLDileveryCountry.SelectedItem.Text.Trim();
        DRDeliveryAdd["place"] = TxtDileveryPlace.Text.Trim();
        DRDeliveryAdd["fax"] = TxtDileveryFax.Text.Trim();
        DRDeliveryAdd["phone"] = TxtDileveryPhone.Text.Trim();
        DRDeliveryAdd["LSTNUM"] = txtVat.Text.Trim();
        DRDeliveryAdd["LSTDATE"] = LstDate;
        DRDeliveryAdd["CSTNUM"] = txtDeliveryInterState.Text.Trim();
        DRDeliveryAdd["CSTDATE"] = CstDate.ToString();
        DRDeliveryAdd["CEPANUM"] = txtDeliveryCENVAT.Text.Trim();
        DRDeliveryAdd["CEPADATE"] = CepDate.ToString();
        DTTemp.Rows.Add(DRDeliveryAdd);
        grdDeliveryAddress.DataSource = DTTemp;
        grdDeliveryAddress.DataBind();
        ViewState["DTDeliveryAddress"] = DTTemp;

    }
    private void _DeleteZeroValueItemInDropdownlist(DropDownList ddl)
    {
        if (ddl.Items.Count > 0)
        {
            for (int i = 0; i < ddl.Items.Count; i++)
            {
                if (ddl.Items[i].Value == "0")
                {
                    ddl.Items.RemoveAt(i);
                    break;
                }
            }
        }
    }
    private void _SetDebitCreditBasedOnGroup(bool DebitOrCredit)
    {
        if (DebitOrCredit == true)
        {
            DDLServices.SelectedValue = "1";
            TxtClosing.Text = "0.00 Cr";
        }
        else
        {
            DDLServices.SelectedValue = "0";
            TxtClosing.Text = "0.00 Dr";
        }
    }
    #region tab management based on grouptree id
    private void _ApplySettings(string strGID)
    {
        if (strGID != string.Empty)
        {
            string strGroupTreeId = string.Empty;
            strsql = "SELECT GROUPTREEID FROM ACC_GRPMAST WHERE GID='" + strGID + "'";
            DataTable DTGid = DU.getdata(strsql);
            if (DTGid.Rows.Count > 0)
            {
                strGroupTreeId = DTGid.Rows[0]["GROUPTREEID"].ToString();
            }
            if (strGroupTreeId != string.Empty)
            {
                string strSubGroupTree = strGroupTreeId.Substring(0, 3);
                #region Group Tree Id start with 001
                if (strSubGroupTree == "001")
                {
                    if (strGroupTreeId.StartsWith("001004"))
                    {
                        if (strGroupTreeId.StartsWith("001004001") || strGroupTreeId.StartsWith("001004002") || strGroupTreeId.StartsWith("001004003"))
                        {
                            //address not delivery , Contract";
                            _DisableAllTab();
                            _EnableAddressAndContract();


                        }
                        else
                        {
                            _DisableAllTab();
                        }
                    }
                    else if (strGroupTreeId.StartsWith("001005"))
                    {
                        if (strGroupTreeId.StartsWith("001005001"))
                        {
                            //taxDetails taxtype(check),Drop,address not delivery , Contract";
                            _DisableAllTab();
                            _EnableAddressAndContract();
                            _EnableTaxDetails(false, false, false, true, true, false, false, false, false);

                        }
                        else if (strGroupTreeId.StartsWith("001005002"))
                        {
                            if (strGroupTreeId.StartsWith("001005002001"))
                            {
                                //full Tab Not taxDetails";
                                _EnableAllTab();
                                tabTaxDetails.Disabled = true;
                                panelTaxDetails.Enabled = false;
                            }
                            else
                            {
                                //taxDetails status,tds,service full Tab";
                                _EnableAllTab();
                                _EnableTaxDetails(true, true, false, false, false, false, false, true, false);

                            }
                        }
                        else if (strGroupTreeId.StartsWith("001005003"))
                        {
                            //taxDetails tds,status,taxtype(check)";
                            _DisableAllTab();
                            _EnableTaxDetails(true, true, false, true, false, false, false, false, false);
                        }
                        else
                        {
                            //taxDetails ttd,status,taxtype(check),address not delivery , Contract, registration";
                            _DisableAllTab();
                            _EnableTaxDetails(true, true, false, true, true, false, false, false, false);
                            _EnableAddressAndContract();
                            tabRegistration.Disabled = false;
                            panelRegistration.Enabled = true;
                        }
                    }
                    else
                    {
                        _DisableAllTab();
                    }
                    _SetDebitCreditBasedOnGroup(true);
                }
                #endregion
                #region Group Tree Id start with 002
                else if (strSubGroupTree == "002")
                {
                    if (strGroupTreeId.StartsWith("002001"))
                    {
                        // "TaxDetails- TDS,Nature, Taxtype(check),Main,Sub";
                        _DisableAllTab();
                        _EnableTaxDetails(true, false, true, true, false, true, true, false, false);
                    }
                    else if (strGroupTreeId.StartsWith("002002"))
                    {
                        //"Address-(not Delivery),Contact";
                        _DisableAllTab();
                        _EnableAddressAndContract();

                    }
                    else if (strGroupTreeId.StartsWith("002003"))
                    {
                        if (strGroupTreeId.StartsWith("002003001"))
                        {
                            if (strGroupTreeId.StartsWith("002003001002") || strGroupTreeId.StartsWith("002003001004"))
                            {
                                _DisableAllTab();
                                _EnableAddressAndContract();
                            }
                            else if (strGroupTreeId.StartsWith("002003001006"))
                            {
                                //"Full But Not Tax Details";
                                _EnableAllTab();
                                tabTaxDetails.Disabled = true;
                                panelTaxDetails.Enabled = false;
                            }
                            else
                            {
                                //None
                                _DisableAllTab();
                            }
                        }
                        else if (strGroupTreeId.StartsWith("002003002"))
                        {
                            if (strGroupTreeId.StartsWith("002003002001") || strGroupTreeId.StartsWith("002003002002"))
                            {
                                //TaxDetails- TDS,Status,Service, Address(not Delivery), Contract, Registration";
                                _DisableAllTab();
                                _EnableTaxDetails(true, true, false, false, false, false, false, true, false);
                                _EnableAddressAndContract();
                                tabRegistration.Disabled = false;
                                panelRegistration.Enabled = true;
                            }
                            else
                            {
                                // "TaxDetails- TDS,Status, Address(not Delivery), Contract, Registration";
                                _DisableAllTab();
                                _EnableTaxDetails(true, true, false, false, false, false, false, false, false);
                                _EnableAddressAndContract();
                                tabRegistration.Disabled = false;
                                panelRegistration.Enabled = true;
                            }
                        }
                        else
                        {
                            _DisableAllTab();
                        }

                    }
                    else
                    {
                        _DisableAllTab();
                    }
                    _SetDebitCreditBasedOnGroup(false);
                }
                #endregion
                #region Group Tree Id start with 003
                else if (strSubGroupTree == "003")
                {
                    if (strGroupTreeId.StartsWith("003001") || strGroupTreeId.StartsWith("003008") || strGroupTreeId.StartsWith("003011"))
                    {
                        //"TaxDetails-CostCenter";
                        _DisableAllTab();
                        _EnableTaxDetails(false, false, false, false, false, false, false, false, true);
                    }
                    else if (strGroupTreeId.StartsWith("003002") || strGroupTreeId.StartsWith("003010"))
                    {
                        //"TaxDetails-TaxType(Check), Main,Sub, Cost";
                        _DisableAllTab();
                        _EnableTaxDetails(false, false, false, true, false, true, true, false, true);
                    }
                    else if (strGroupTreeId.StartsWith("003003") || strGroupTreeId.StartsWith("003004") || strGroupTreeId.StartsWith("003009"))
                    {
                        //"TaxDetails- TDS,Nature, Taxtype(check),Main,Sub, Cost";
                        _DisableAllTab();
                        _EnableTaxDetails(true, false, true, true, false, true, true, false, true);
                    }
                    else if (strGroupTreeId.StartsWith("003005") || strGroupTreeId.StartsWith("003006") || strGroupTreeId.StartsWith("003007"))
                    {
                        //"TaxDetails- TDS,Nature,  Cost";
                        _DisableAllTab();
                        _EnableTaxDetails(true, false, true, false, false, false, false, false, true);
                    }
                    else
                    {
                        //"TaxDetails- TDS,Nature, Taxtype(check),Main,Sub, Cost";
                        _DisableAllTab();
                        _EnableTaxDetails(true, false, true, true, false, true, true, false, true);
                    }
                    _SetDebitCreditBasedOnGroup(false);
                }
                #endregion
                #region Group Tree Id start with 004
                else if (strSubGroupTree == "004")
                {
                    if (strGroupTreeId.StartsWith("004001") || strGroupTreeId.StartsWith("004005"))
                    {
                        //"TaxDetails-TaxType(Check), Main,Sub, Cost";
                        _DisableAllTab();
                        _EnableTaxDetails(false, false, false, true, false, true, true, false, true);
                    }
                    else
                    {
                        //"TaxDetails-CostCenter";
                        _DisableAllTab();
                        _EnableTaxDetails(false, false, false, true, false, false, false, false, true);
                    }
                    _SetDebitCreditBasedOnGroup(true);
                }
                #endregion
                #region Group Tree Id start with 005
                else if (strSubGroupTree == "005")
                {
                    //"Full But Not Tax Details";
                    _EnableAllTab();
                    tabTaxDetails.Disabled = true;
                    panelTaxDetails.Enabled = false;

                }
                #endregion
                #region Group Tree Id start with 006
                else
                {
                    //None
                    _DisableAllTab();
                }
                #endregion                
            }
        }
    }
    private void _DisableAllTab()
    {
        tabTaxDetails.Disabled = true;
        tabAddress.Disabled = true;
        tabContact.Disabled = true;
        tabRegistration.Disabled = true;
        tabOtherDetails.Disabled = true;
        tabTermAndConditions.Disabled = true;
        lnkDilevery.Enabled = false;
        modalDelivery.Enabled = false;

        _ClearControl(panelTaxDetails);
        _ClearControl(panelAddress);
        _ClearControl(panelContact);
        _ClearControl(panelOtherDetails);
        _ClearControl(panelRegistration);
        _ClearControl(panelTermAndCondition);

        panelTaxDetails.Enabled = false;
        panelAddress.Enabled = false;
        panelContact.Enabled = false;
        panelOtherDetails.Enabled = false;
        panelRegistration.Enabled = false;
        panelTermAndCondition.Enabled = false;
    }
    private void _EnableAllTab()
    {
        tabTaxDetails.Disabled = false;
        tabAddress.Disabled = false;
        tabContact.Disabled = false;
        tabRegistration.Disabled = false;
        tabOtherDetails.Disabled = false;
        tabTermAndConditions.Disabled = false;
        lnkDilevery.Enabled = true;
        modalDelivery.Enabled = true;

        _ClearControl(panelTaxDetails);
        _ClearControl(panelAddress);
        _ClearControl(panelContact);
        _ClearControl(panelOtherDetails);
        _ClearControl(panelRegistration);
        _ClearControl(panelTermAndCondition);

        panelTaxDetails.Enabled = true;
        panelAddress.Enabled = true;
        panelContact.Enabled = true;
        panelOtherDetails.Enabled = true;
        panelRegistration.Enabled = true;
        panelTermAndCondition.Enabled = true;
        txtAddName.Text = TxtName.Text;
    }
    private void _EnableAddressAndContract()
    {

        tabAddress.Disabled = false;
        tabContact.Disabled = false;
        _ClearControl(panelAddress);
        _ClearControl(panelContact);
        panelAddress.Enabled = true;
        panelContact.Enabled = true;
        txtAddName.Text = TxtName.Text;
    }
    private void _EnableTaxDetails(bool TDS, bool Status, bool Nature, bool taxTypeC, bool taxTypeD, bool MainClass, bool SubClass, bool ServiceTax, bool CostCenter)
    {
        tabTaxDetails.Disabled = false;
        panelTaxDetails.Enabled = true;

        ChkTDS.Enabled = TDS;
        if (TDS == true)
        {
            if (Status == true)
            {
                lblTDSStatus.Visible = true;
                lblTDSNature.Visible = false;
                DDLStatus.Visible = true;
                DDLStatus.Enabled = true;
                ddlTDSNature.Enabled = false;
                ddlTDSNature.Visible = false;
                hidTdsStatus.Value = "1";
            }
            else if (Nature == true)
            {
                lblTDSNature.Visible = true;
                lblTDSStatus.Visible = false;
                ddlTDSNature.Enabled = true;
                ddlTDSNature.Visible = true;
                DDLStatus.Visible = false;
                DDLStatus.Enabled = false;
                hidTdsStatus.Value = "2";
            }
        }
        else
        {
            hidTdsStatus.Value = "0";
            DDLStatus.Enabled = false;
            ddlTDSNature.Enabled = false;
        }
        ChkTaxType.Enabled = taxTypeC;
        DDLTaxType.Enabled = taxTypeD;
        DDLMainClass.Enabled = MainClass;
        DDLSubClass.Enabled = SubClass;
        ChkService.Enabled = ServiceTax;
        ChkCost.Enabled = CostCenter;
    }
    private void _ClearControl(Control ParentControl)
    {
        foreach (Control c in ParentControl.Controls)
        {
            if ((c.GetType()) == typeof(TextBox))
            {
                ((TextBox)(c)).Text = "";
            }
            if ((c.GetType()) == typeof(DropDownList))
            {
                if (((DropDownList)(c)).Items.Count > 0)
                {
                    for (int i = 0; i < ((DropDownList)(c)).Items.Count; i++)
                    {
                        if (((DropDownList)(c)).Items[i].Value == "0")
                        {
                            ((DropDownList)(c)).SelectedValue = "0";
                            break;
                        }
                    }
                }
            }
            if ((c.GetType()) == typeof(CheckBox))
            {
                ((CheckBox)(c)).Checked = false;
            }
            if ((c.GetType()) == typeof(ListBox))
            {
                ((ListBox)(c)).SelectedValue = "0";
            }
            _ClearControl(c);
        }
    }
    #endregion
}



